package com.example.demo02.utils;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo02.common.BaseRequest;
import com.example.demo02.constants.AttributeConstant;
import com.example.demo02.constants.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.ObjectUtils;

import static cn.hutool.core.text.StrPool.EMPTY_JSON;
@Slf4j
public class HelpUtil {
    private static final String PRIVATE_KEY= Opt.ofTry(()->RsaUtil2.getPrivateKey(AttributeConstant.RSA_PRIVATE_KEY)).get();

    public static String convertToDisplayPrice(String price){
        return NumberUtil.isNumber(price)?NumberUtil.toStr(NumberUtil.div(price, CommonConstant.HUNDRED,2)):"";
    }
    public static String convertToDisplayPrice(Number price) {
        return ObjectUtils.isEmpty(price) ? "0" : convertToDisplayPrice(price.toString());
    }

    public static boolean isProjectRequestBody(Object arg) {
        //参数为空，返回false
        if(ObjectUtil.isNull(arg))return false;
        Class<?> argumentClass = arg.getClass();
        return ClassUtil.isBasicType(argumentClass) || ClassUtil.getPackage(argumentClass).startsWith("com.example");
    }

    public static String decryptData(Opt<BaseRequest> baseRequestOpt) {
        String data = baseRequestOpt.map(BaseRequest::getData).get();
        String aesKey = baseRequestOpt.map(BaseRequest::getAesKey).get();
        if(StrUtil.hasBlank(data,aesKey))return StrPool.EMPTY_JSON;
        try {
            String decryptAesKey=new String(RsaUtil2.decryptByPrivateKey(Base64.decodeBase64(aesKey),PRIVATE_KEY));
            String decryptData=AesUtil.decrypt(data,decryptAesKey);
            return StrUtil.isBlankOrUndefined(decryptData)?EMPTY_JSON:decryptData;
        } catch (Exception e) {
            log.error("参数解密时遇到错误, 原因: [{}]", e.getMessage());
            return EMPTY_JSON;
        }
    }
}
